var fs = require('fs'),
    path = require('path'),
    sidebar = require('../helpers/sidebar');

module.exports = {
    index: function (req, res) {

        var viewModel = {
            image: {
                uniqueId: 1,
                title: '图片1',
                description: 'Saber.',
                filename: 'sample1.jpg',
                views: 0,
                likes: 0,
                timestamp: Date.now()
            },
            comments: [
                {
                    image_id: 1,
                    email: 'test@testing.com',
                    name: 'Aimee',
                    gravatar: 'http://www.gravatar.com/avatar/9a99fac7b524fa443560ec7b5ece5ca1?d=monsterid&s=45',
                    comment: 'Sabar真美...',
                    timestamp: Date.now()
                }, {
                    image_id: 1,
                    email: 'test@testing.com',
                    name: 'joly',
                    gravatar: 'http://www.gravatar.com/avatar/9a99fac7b524fa443560ec7b5ece5ca1?d=monsterid&s=45',
                    comment: '不错!',
                    timestamp: Date.now()
                }
            ]
        };

        // res.render('image', viewModel);
        sidebar(viewModel, function (viewModel) {
            res.render('image', viewModel);
        })
    },

    create: function (req, res) {
        var saveImage = function () {
            var possible = 'abcdefghijklmnopqrstuvwxyz0123456789',
                imgurl = '';

            for(var i = 0; i < 6; i++){
                imgurl += possible.charAt(Math.floor(Math.random() * possible.length));
            }

            var tempPath = req.files.file.path,
                ext = path.extname(req.files.file.name).toLowerCase(),
                targetPath = path.resolve('./public/upload/' + imgurl + ext);

            if(ext === '.png' || ext === '.jpg' || ext === ext === '.jpeg' || ext === '.gif'){
                fs.rename(tempPath, targetPath, function (err) {
                    if(err) throw err;
                    res.redirect('/images/' + imgurl);
                });
            }else{
                fs.unlink(tempPath, function (err) {
                    if(err) throw err;

                    // res.json(500, {error: '只允许上传图片文件！'});
                    res.status(500);
                    res.send("只允许上传图片文件！");
                })
            }

        }
        saveImage();
    },

    like: function (req, res) {
        res.send("The image: like POST controller.");
    },

    comment: function (req, res) {
        res.send("The image: comment POST cotrroller");
    }
}

